import React, { useEffect, forwardRef, useImperativeHandle } from 'react';
import { Spin, Row, Col, Space, Select } from 'antd';
import { features, useTablePipeline } from 'ali-react-table';

import { useTRState } from '#/utils/trHooks.jsx';
import { TjChart, TjTable, TjSegmented } from '@/pages/ETrade/components';
import { export_json_to_excel } from '@/utils/fileExport.js';
import { ChartTitle } from '../components';
import { DATA_MAP, getTableColumns, fmtData } from '../helper';
import { getRunDataList, getSpotPrice } from '../services';
import { useThemeChange } from '@/hooks';

// 山西
export default forwardRef(({ formValue, stations, marketName, marketId, isRe }, ref) => {
  const _charts = [
    'spotPrice',
    'biddingSpace',
    'biddingSpaceCorrelationMap',
    'provinceLoadLink',
    'provinceLoadNewEnergy',
    'newEnergy',
    'provinceLoad',
    'link',
    'totalOutputOfNonmarketizedGeneratingUnits',
    'totalOutputOfHydropowerIncludingPumpedStorage',
    'setTheStandby',
  ];
  const _table = [
    'spotPrice',
    // 'provinceLoadLinkNewEnergy',
    // 'provinceLoadLink',
    // 'provinceLoadNewEnergy',
    'provinceLoad',
    'link',
    'newEnergy',
    'baseDecompositionProportion',
    'setTheStandby',
  ];
  const [state, setState] = useTRState({
    loading: true,
    loadingSpot: true,
    // 场站
    stationName: stations?.[0]?.label || '',
    // form
    stationId: stations?.[0]?.value || null,
    isRevised: 1, // 修正前(0)/后(1)
    // result
    dataMap: {}, // 原始数据(未处理)
    tableColumns: [], // 表头
    tableData: [], // 表数据
    charts: {}, // 图配置 charts[key] 与 _charts[key] 对应
    datetimes: [], // 时间刻度
  });
  const { theme } = useThemeChange();

  useImperativeHandle(ref, () => ({
    onFetch,
    onExport,
  }));

  useEffect(() => {
    // 表头、时间刻度：依赖时间范围、点位类型
    const tableColumns = getTableColumns(formValue);
    const datetimes = tableColumns.slice(1).map((x) => x.name);
    setState({
      datetimes,
      tableColumns,
    });
  }, [formValue.startDate, formValue.endDate, formValue.type]);
  useEffect(() => {
    // 交易中心切换
    setState({
      // 场站
      stationName: stations?.[0]?.label || '',
      // form
      stationId: stations?.[0]?.value || null,
    });
    // onFetchSpot();
  }, [marketId, isRe]);

  useEffect(() => {
    // 数据全部获取后处理
    if (state.loadingSpot) return;
    if (Object.keys(state.dataMap).length < _charts.length) return;
    setTimeout(() => {
      const { charts, tableData } = fmtData({
        dataMap: state.dataMap,
        datetimes: state.datetimes,
        isRevised: state.isRevised,
        stationName: state.stationName,
        chartKeys: _charts,
        tableKeys: _table,
      });
      setState({
        charts,
        tableData,
      });
    }, 1);
  }, [JSON.stringify(state.dataMap), state.isRevised, state.loadingSpot, theme]);

  /** 数据处理 */
  async function onFetch() {
    await Promise.all([onFetchData(), onFetchSpot()]);
  }
  function onExport() {
    if (state.loading || state.loadingSpot) return;
    // 导出
    let exportData = [];
    state.tableData.map(({ groupTitle, children }) => {
      exportData.push([groupTitle]);
      exportData = exportData.concat(
        children.map((c) => state.tableColumns.map(({ code }) => c[code])),
      );
    });
    const params = {
      header: state.tableColumns.map((c) => c.name),
      data: exportData,
      filename: `运行数据披露-${marketName}`,
    };
    export_json_to_excel(params);
  }

  async function onFetchSpot() {
    // 现货价格、竞价空间
    setState({ loadingSpot: true });
    const { stationId } = state;
    const res = await getSpotPrice({ ...formValue, stationId });
    state.dataMap = {
      ...state.dataMap,
      ...(res?.runDataPointBodyMap || {}),
      biddingSpaceCorrelationMap: res?.biddingSpaceCorrelationMap || {},
    };
    setState({
      dataMap: state.dataMap,
      loadingSpot: false,
    });
    return Promise.resolve();
  }

  async function onFetchData() {
    // 其他数据
    setState({ loading: true });
    const res = await getRunDataList(formValue);
    state.dataMap = {
      ...state.dataMap,
      ...(res?.runDataPointBodyMap || {}),
    };
    setState({
      dataMap: state.dataMap,
      loading: false,
    });
    return Promise.resolve();
  }

  /** 方法 */
  const onChangeStation = (v, opt) => {
    // 场站切换
    state.stationId = v;
    state.stationName = opt.label;
    setState({
      stationId: state.stationId,
      stationName: state.stationName,
    });
    onFetchSpot();
  };

  const onChangeRevised = (isRevised) => {
    state.isRevised = isRevised;
    setState({ isRevised });
  };

  /** render */
  const pipeline = useTablePipeline()
    .input({
      columns: state.tableColumns,
      dataSource: state.tableData,
    })
    .primaryKey('id')
    .use(features.rowGrouping({ defaultOpenAll: true }))
    .appendRowPropsGetter((record) => {
      const color = !!record.groupTitle ? '#2D3133' : '#222629';
      return {
        style: { '--bgcolor': color, '--hover-bgcolor': color },
      };
    });

  // 所有图
  const _renderCharts = () =>
    _charts.map((key) => {
      const { group, ...titleProps } = DATA_MAP[key] || {};
      if (key === 'spotPrice') {
        // 现货价格
        titleProps.right = (
          <Space size={16}>
            <Select
              style={{ width: 200 }}
              value={state.stationId}
              options={stations}
              optionFilterProp="label"
              showSearch
              showArrow
              onChange={onChangeStation}
              getPopupContainer={(e) => e.parentNode}
            />
            <TjSegmented
              value={state.isRevised}
              options={[
                { label: '修正前', value: 0 },
                { label: '修正后', value: 1 },
              ]}
              onChange={onChangeRevised}
            />
          </Space>
        );
      }
      if (key === 'biddingSpaceCorrelationMap') {
        // 现货价格&竞价空间相关性
        titleProps.right = <div style={{ color: '#7A7D7F' }}>{state.stationName}</div>;
      }
      const selfLoading = key === 'spotPrice' || key === 'biddingSpaceCorrelationMap';
      return (
        <Col span={12} key={key}>
          <Spin spinning={selfLoading && !state.loading && state.loadingSpot}>
            <div>
              <ChartTitle {...titleProps} />
              <TjChart style={{ height: 200 }} option={state.charts?.[key] || null} group={group} />
            </div>
          </Spin>
        </Col>
      );
    });

  return (
    <div>
      <Spin spinning={state.loading}>
        <Row gutter={[24, 24]}>
          {_renderCharts()}
          <Col span={24}>
            <div>
              <TjTable
                isLoading={!state.loading && state.loadingSpot}
                useVirtual="auto"
                defaultColumnWidth={90}
                {...pipeline.getProps()}
              />
              <div style={{ height: 24 }} />
            </div>
          </Col>
        </Row>
      </Spin>
    </div>
  );
});
